// @ts-check
const postcss = require('postcss')

/**
 * @param {{ namespace: string, ignore?: RegExp }} options
 * @returns {postcss.AcceptedPlugin}
 */
const namespacePluginForPostcss = (options) => {
    return {
        postcssPlugin: 'plugin-namespace',
        Rule: async (rule) => {
            if (!rule.selectors) {
                return
            }
            if (rule.parent?.type != 'root' && rule.parent?.type != 'rule') {
                return
            }
            rule.selectors = rule.selectors.map(selector => {
                return selector.split(',').map(item => {
                    if (options.ignore?.test(item.trim())) {
                        return item
                    }
                    return `${options.namespace} ${item}`
                }).join(',')
            })
        }
    }
}

module.exports = namespacePluginForPostcss